#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 rambla.eu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.import os
import platform, os, sys, datetime, time
import json
import unittest
import setup_environ
from setup_environ import *
import raws_json
from raws_json.raws_service import RawsService, Feed, Query
from raws_json.rats.service import RatsService


class JobTest(unittest.TestCase):
    
    @classmethod
    def setUpClass(cls):
        cls.service = RatsService(username = setup_environ.TEST_USERNAME, password = setup_environ.TEST_PASSWORD, server = setup_environ.TEST_SERVER)
        print "JobTest: starting to upload src, please wait..."
        cls.src_entry = cls.service.createSrc(filename = "unittest_py", local_path = LOCAL_FILE)
        print "JobTest: finished uploading src"

    def setUp(self):
        """ Delete all content for the account before running each test. """
        pass
        
    def poll_job(self, job_entry, job_description):
        """ Polls until job is complete, returns tuple status, entry. 
        
            @param job_entry Dict containing a job entry dict... (json job entry decoded)
            @param job_description Plain text to describe the job (for printing to stdout).
            @return Tuple: status (int, '-1' if job_entry is not valid), job_entry (of the completed job).
        """
        status = -1
        # check if the job entry is valid
        if job_entry.has_key("entry"):
            if job_entry["entry"].has_key("content"):
                if job_entry["entry"]["content"].has_key("params"):
                    if job_entry["entry"]["content"]["params"].has_key("status"):
                        status = job_entry["entry"]["content"]["params"]["status"]
        if status == -1:
            return -1, None
        # if the job entry is valid, poll until job is complete
        while int(job_entry["entry"]["content"]["params"]["status"]) < 7:
            print "status = %s for %s job, polling..." % (job_entry["entry"]["content"]["params"]["status"], job_description)
            job_entry = self.service.getJob(uri = job_entry["entry"]["id"])
            time.sleep(5)
        return int(job_entry["entry"]["content"]["params"]["status"]), job_entry
    
    # def test_create_job__single_format(self):
    #     """ Create content with only content.name + file set. """
    #     job_entry = self.service.createJob(format="1", output = "1", src_location=self.src_entry["entry"]["content"]["params"]["filename"])
    #     self.assertTrue(job_entry["entry"]["content"]["params"]["id"])
    #     status, job_entry = self.poll_job(job_entry, "test_create_job__single_format")
    #     self.assertEqual(status, 7)
    # 
    # def test_create_job__client_passthru_clean(self):
    #     """ Create content with only content.name + file set. """
    #     job_entry = self.service.createJob(format="1", output = "1", src_location=self.src_entry["entry"]["content"]["params"]["filename"], proc = "1,8,24", client_passthru = u"&lt;?xml version='1.0'?&gt;&lt;meta&gt;&lt;name&gt;&lt;![CDATA[eeees]]&gt;&lt;\/name&gt;\n\t\t\t&lt;firstname&gt;&lt;![CDATA[test]]&gt;&lt;\/firstname&gt;&lt;description&gt;&lt;![CDATA[tereas]]&gt;&lt;\/description&gt;&lt;email&gt;&lt;![CDATA[rrsdss@aa.dddd]]&gt;&lt;\/email&gt;&lt;thumbnail&gt;&lt;![CDATA[1333031194-20.jpg]]&gt;&lt;\/thumbnail&gt;&lt;source&gt;&lt;![CDATA[1333031194]]&gt;&lt;\/source&gt;&lt;\/meta&gt;")
    #     self.assertTrue(job_entry["entry"]["content"]["params"]["id"])
    #     status, job_entry = self.poll_job(job_entry, "test_create_job__client_passthru_clean")
    #     self.assertEqual(status, 7)
        
    def test_create_job__client_passthru_dirty(self):
        """ Create content with only content.name + file set. """
        client_passthru = unicode("héùiuà", "utf8")
        job_entry = self.service.createJob(format="1", output = "1", src_location=self.src_entry["entry"]["content"]["params"]["filename"], client_passthru = client_passthru, proc = "1,8,24,56")
        self.assertTrue(job_entry["entry"]["content"]["params"]["id"])
        status, job_entry = self.poll_job(job_entry, "test_create_job__client_passthru_dirty")
        self.assertEqual(status, 7)
        self.assertEqual(job_entry["entry"]["content"]["params"]["client_passthru"], client_passthru)

    # def test_create_job__client_passthru_dirty(self):
    #     """ Create content with only content.name + file set. """
    #     client_passthru = unicode("héùiuà", "utf8")
    #     job_entry = self.service.createJob(format="1", output = "1", src_location=self.src_entry["entry"]["content"]["params"]["filename"], client_passthru = client_passthru, proc = "1,8,24")
    #     self.assertTrue(job_entry["entry"]["content"]["params"]["id"])
    #     status, job_entry = self.poll_job(job_entry, "test_create_job__client_passthru_dirty")
    #     self.assertEqual(status, 7)
    # 
    #         
    # def test_create_job__client_passthru_latin_1(self):
    #     """ Create content with latin-1 charset: job should succeed but client_passthru will be modified (stored and retrieved as utf8).
    #     
    #         In order to encode/decode this string as part of json/xml reports, we need it to be encoded using the same character set as the rest of the report!
    #     """
    #     client_passthru = unicode("mémésseà", "latin-1")
    #     job_entry = self.service.createJob(format="1", output = "1", src_location=self.src_entry["entry"]["content"]["params"]["filename"], client_passthru = client_passthru, proc = "1,8,24")
    #     self.assertTrue(job_entry["entry"]["content"]["params"]["id"])
    #     status, job_entry = self.poll_job(job_entry, "test_create_job__client_passthru_latin_1")
    #     self.assertEqual(status, 7)


    # def test_create_job__client_passthru(self):
    #     """ Create content with only content.name + file set. """
    #     resp = self.service.createJob(format="1", src_location="big_buck_bunny", client_passthru = "<ik ben niet >zot/ ?")
    #     print resp
        
def suite():
   suite = unittest.TestSuite()
   suite.addTest(unittest.makeSuite(JobTest))
   return suite

if __name__=='__main__':
    unittest.main()
